const remoteMenu = require('remoteMenuRenderer.js')
const browserUI = require('browserUI.js')
const webviews = require('webviews.js')
const readerView = require('readerView.js')
const urlParser = require('util/urlParser.js')

// 检测是否为鸿蒙平台（渲染进程）
function isHarmonyOSPlatform () {
  // 方法1: 检查 navigator.platform（鸿蒙可能返回特定值）
  const platform = navigator.platform
  
  // 方法2: 检查 userAgent
  const userAgent = navigator.userAgent
  
  // 如果 platform 不是常见的 MacIntel/Win32/Linux，可能是鸿蒙
  const commonPlatforms = ['MacIntel', 'Win32', 'Linux x86_64', 'Linux']
  if (platform && !commonPlatforms.some(p => platform.includes(p))) {
    console.log('检测到非标准平台，可能是鸿蒙系统:', platform)
    return true
  }
  
  // 检查 userAgent 中是否包含鸿蒙标识
  if (userAgent && (userAgent.includes('HarmonyOS') || userAgent.includes('OHOS'))) {
    console.log('检测到鸿蒙 userAgent:', userAgent)
    return true
  }
  
  // 检查 window.platformType（如果已设置）
  if (window.platformType && window.platformType !== 'mac' && 
      window.platformType !== 'windows' && window.platformType !== 'linux') {
    return true
  }
  
  return false
}

const tabContextMenu = {
  show: function (tabId) {
    const tabMenu = [
      [
        {
          label: l('appMenuDuplicateTab'),
          click: function () {
            const sourceTab = tabs.get(tabId)
            // strip tab id so that a new one is generated
            const newTab = tabs.add({ ...sourceTab, id: undefined })

            browserUI.addTab(newTab, { enterEditMode: false })
          }
        }
        // 检测是否为鸿蒙平台，如果是则隐藏"新窗口"菜单项
        // ...(isHarmonyOSPlatform() ? [] : [
        //   {
        //     label: l('tabMenuNewWindow'),
        //     click: function () {
        //       // insert after current task
        //       let index
        //       if (tasks.getSelected()) {
        //         index = tasks.getIndex(tasks.getSelected().id) + 1
        //       }
        //       const newTask = tasks.get(tasks.add({}, index))
        //
        //       const targetTab = tabs.get(tabId)
        //       tabs.destroy(targetTab.id)
        //
        //       newTask.tabs.add(targetTab)
        //
        //       ipc.send('newWindow', { initialTask: newTask.id })
        //
        //       browserUI.switchToTask(tasks.getSelected().id)
        //     }
        //   }
        // ])
      ]
    ]

    // 如果不是鸿蒙平台，添加"新窗口"菜单项
    if (!isHarmonyOSPlatform()) {
      tabMenu[0].push({
        label: l('tabMenuNewWindow'),
        click: function () {
          // insert after current task
          let index
          if (tasks.getSelected()) {
            index = tasks.getIndex(tasks.getSelected().id) + 1
          }
          const newTask = tasks.get(tasks.add({}, index))

          const targetTab = tabs.get(tabId)
          tabs.destroy(targetTab.id)

          newTask.tabs.add(targetTab)

          ipc.send('newWindow', { initialTask: newTask.id })

          browserUI.switchToTask(tasks.getSelected().id)
        }
      })
    } else {
      console.log('鸿蒙平台：已隐藏标签页右键菜单中的"新窗口"选项')
    }

    if (tabs.get(tabId).url && (readerView.isReader(tabId) || !urlParser.isInternalURL(tabs.get(tabId).url))) {
      if (!readerView.isReader(tabId)) {
        tabMenu[0].push({
          label: l('enterReaderView'),
          click: function () {
            readerView.enter(tabId, tabs.get(tabId).url)
          }
        })
      } else {
        tabMenu[0].push({
          label: l('exitReaderView'),
          click: function () {
            readerView.exit(tabId)
          }
        })
      }
    }

    tabMenu[0].push( {
      label: l('tabMenuReload'),
      click: function () {
        if (tabs.get(tabId).url.startsWith(webviews.internalPages.error)) {
          // reload the original page rather than show the error page again
          webviews.update(tabId, new URL(tabs.get(tabId).url).searchParams.get('url'))
        } else {
          // this can't be an error page, use the normal reload method
          webviews.callAsync(tabId, 'reload')
        }
      }
    })

    remoteMenu.open(tabMenu)
  },
  initialize: function () {
    const container = document.getElementById('tabs-inner')
    container.addEventListener('contextmenu', function (e) {
      let node = e.target

      while (node) {
        if (node.classList.contains('tab-item')) {
          tabContextMenu.show(node.getAttribute('data-tab'))
          e.stopPropagation()
          break
        }
        node = node.parentNode
      }
    })
  }
}

module.exports = tabContextMenu
